// $Id: simple_cart.js,v 1.2 2011/01/25 18:16:14 vladsavitsky Exp $
/*
 * @file
 * Contains JS code to handle 'Add to Cart' links using AJAX.
 */
Drupal.behaviors.SimpleCartAddToCartButton = function (context) {
  function highlightItem($item) {
    var InitBbackgroundColor = $item.css('backgroundColor');
    if (jQuery().effect) {
      $item.effect("highlight", {color : 'silver'}, 1500);
    }
    else {
      $item.css('backgroundColor', 'silver');
      function ChangeBackground (vars) {
        vars[0].css('backgroundColor', vars[1]);
      }
      window.setTimeout(ChangeBackground, 1500, [$item, InitBbackgroundColor]);
    }
  }
  /**
   * AJAX request for adding item to cart or removing item from cart.
   */
  var itemAjaxRequest = function(nodeID, op, $currentLink, context) {
    if (typeof ($currentLink) != 'undefined'
        && nodeID != null
        && (op == 'add' || op == 'remove')) {

      var $throbber = $currentLink.next('.simple-cart-throbber');
      // Cart List Block:
      var $cartListBlock = $('#cart-list-block', context);
      var $cartListBlockContext = $cartListBlock.parent().parent();
      var $currentItem = $('#cart-block-item-' + nodeID, $cartListBlockContext)
      var $parentLiForCurrentItem = $currentItem.parent();
      // Cart Icon Block:
      var $cartIconBlock = $('#simple-cart-icon');

      $throbber.show();
      $currentLink.hide();
      $.ajax({
        url: Drupal.settings.basePath + '?q=simple_cart_js',
        data: {'nid' : nodeID, 'op': op},
        dataType: 'json',
        type: "POST",
        success: function(data) {
          // Cart Icon Block update:
          if ($cartIconBlock.size()) {
            if (data.total_items_count <=0) {
              data.total_items_count = '';
            }
            $('#items-counter', $cartIconBlock).text(data.total_items_count);
          }
          // Cart List Block update:
          if (op == 'add') {
            // Update item info in cart block if block present at page:
            if ($cartListBlock.size()) {
              var currentBlockItem = $('#cart-block-item-' + nodeID, $cartListBlockContext);
              if (currentBlockItem.length) {
                // Change item's quantity in cart block:
                currentBlockItem.parent().find('span.cart-item-quantity').text(data.quantity);
                highlightItem(currentBlockItem.parent());
              }
              else {
                // Cart was empty so we add new item:
                $('#cart-block-empty-message', $cartListBlockContext).hide();
                $cartListBlock.append(data.cart_block_item);
                highlightItem($('#cart-block-item-' + nodeID).parent());
                Drupal.attachBehaviors($cartListBlockContext);
              }
              $('#cart-block-total', $cartListBlockContext).fadeIn('slow');
            }
          }
          else if (op == 'remove') {
            // If leaves only one items in cart - show empty cart message:
            if ($cartListBlock.find('li').length <= 1) {
              $('#cart-block-item-' + nodeID, $cartListBlockContext).parent('li').remove();
              $('#cart-block-total', $cartListBlockContext).hide();
              $('#cart-block-empty-message', $cartListBlockContext).fadeIn('slow');
            }
            else {
              $('#cart-block-item-' + nodeID, $cartListBlockContext).parent('li').fadeOut('slow', function() {$(this).remove();});
            }
          }
          // Change total price:
          $('#cart-block-total-price', context).text(Drupal.parseNumber(data.total_price));
          $throbber.hide();
          $currentLink.show();
        },
        error: function(XMLHttpRequest) {
          alert(Drupal.t("AJAX request error: !status !statusText.",
              {'!status' : XMLHttpRequest.status, '!statusText' : XMLHttpRequest.statusText}
          ));
          $throbber.hide();
          $currentLink.show();
          window.location = $(this).attr('href');
        }
      });
    }
  }

  /**
   * Event handler for click at 'Add to Cart' button of nodes and items in cart block (list).
   */
  $('a.cart-action-button', context).click(function(e) {
    e.preventDefault();
    var $currentLink = $(this);
    var isFound = $(this).attr('href').match(/cart\/(\w+)\/(\d+)/i);

    if (isFound != null) {
      var op = isFound[1];
      var nodeID = isFound[2];
      itemAjaxRequest(nodeID, op, $currentLink, context);
    }
    else {
      alert(Drupal.t("Can't find nodes ID. Check if URL is correct, please."));
    }
  });
  /**
   * Highlight item when mouse over in cart (list) block
   */
  $('#cart-list-block li', context).hover(
    function () {
      $(this).addClass('hover');
    },
    function () {
      $(this).removeClass('hover');
    }
  );
}
